﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using WebApp.Code;
using WindowsSignInPage;

namespace WebApp
{
    public partial class Upload : System.Web.UI.Page
    {
        public string CurrentPath
        {
            get
            {
                return Cache[UserName] as string;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Files.Count > 0 && ImpersonateUser())
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFile file = Request.Files[i];
                    if (null == file || file.ContentLength == 0)
                    {
                        return;
                    }

                    string filename = Path.GetFileName(file.FileName);
                    string fullFilename = Path.Combine(CurrentPath, filename);

                    file.SaveAs(fullFilename);
                }

            }
        }

        protected bool ImpersonateUser()
        {
            string currentUser = Request.RequestType == "POST"
                ? UploadContext.GetUploadUserName()
                : Authentication.GetCurrentUser();
            //string currentUser = "moss2010";

            if (string.IsNullOrEmpty(currentUser))
            {
                string logonUrl = Authentication.GetLogonUrl();
                Response.Redirect(logonUrl);
            }

            loginUser = new LoginUser(currentUser);
            return WindowsContext.Instance.ImpersonateValidUser(UserName, Domain, Password);
        }

        protected LoginUser loginUser { get; set; }
        public string Domain
        {
            get
            {
                return "ceibs.edu";
            }
        }

        public string UserName
        {
            get
            {
                return loginUser.LoginId;
            }
        }

        public string Password
        {
            get
            {
                return EncryptTool.Decrypt(loginUser.Pwd);
            }
        }
    }
}